import {
  findAllDbTypesReq,
  findDatasourcesByTypeReq,
  findDbsByDatasourceIdReq,
  findTablesByDsAndDbReq
} from '@/service/modules/data-manage'
import { reactive } from 'vue'

//数据源公共方法
export function useDatasource() {
  const dsVariables = reactive({
    dsTypeOptions: new Array<{ value: number; label: string }>(),
    dsOptions: new Array<{ value: number; label: string }>(),
    dbOptions: new Array<{ value: string; label: string }>(),
    tableOptions: new Array<{ value: string; label: string }>()
  })
  const getDsTypeOptions = async () => {
    const res = await findAllDbTypesReq()
    if (res.resp_code === 0) {
      res.data.map((item: any) =>
        dsVariables.dsTypeOptions.push({
          value: item,
          label: item
        })
      )
    }
  }
  const getDatasourceByType = async (type: string) => {
    dsVariables.dsOptions = []
    const res = await findDatasourcesByTypeReq({ dbType: type })
    if (res.resp_code === 0) {
      res.data.map((item: any) =>
        dsVariables.dsOptions.push({
          value: item.id,
          label: item.name
        })
      )
    }
  }
  const getDbsByDatasourceId = async (datasourceId: number) => {
    dsVariables.dbOptions = []
    const res = await findDbsByDatasourceIdReq({ datasourceId: datasourceId })
    if (res.resp_code === 0) {
      res.data.map((item: any) =>
        dsVariables.dbOptions.push({
          value: item.dbName,
          label: item.dbName
        })
      )
    }
  }
  const getTablesByDsAndDb = async (datasourceId: number, dbName: string) => {
    dsVariables.tableOptions = []
    const res = await findTablesByDsAndDbReq({
      datasourceId: datasourceId,
      dbName: dbName
    })
    if (res.resp_code === 0) {
      res.data.map((item: any) =>
        dsVariables.tableOptions.push({
          value: item.tableName,
          label: item.tableName
        })
      )
    }
  }
  return {
    dsVariables,
    getDsTypeOptions,
    getDatasourceByType,
    getDbsByDatasourceId,
    getTablesByDsAndDb
  }
}
